import path from "path";
import { fileURLToPath } from "url";

const config = {
  label: "用户",
};

export default async function (app) {
  // 获取当前文件名称
  const fileName = path.basename(fileURLToPath(import.meta.url), ".js");
  // 获取数据库集合【表】
  const collection = app.mongo.db.collection(fileName + "s");

  // 列表
  app.get("/list", async (request, reply) => {
    try {
      const list = await collection.find().toArray();
      return {
        success: true,
        count: list.length,
        data: list,
      };
    } catch (error) {
      app.log.error("获取" + config.label + "列表失败:", error);
      return reply.code(500).send({
        success: false,
        error: "获取" + config.label + "列表失败",
      });
    }
  });

  // 详情
  app.get("/detail/:id", async (request, reply) => {
    try {
      // 在请求处理函数中获取数据库集合和 ObjectId
      const { ObjectId } = app.mongo;

      const detail = await collection.findOne({
        _id: new ObjectId(request.params.id),
      });

      if (!detail) {
        return reply.code(404).send({
          success: false,
          error: config.label + "不存在",
        });
      }

      return {
        success: true,
        data: detail,
      };
    } catch (error) {
      app.log.error("获取" + config.label + "详情失败:", error);
      return reply.code(500).send({
        success: false,
        error: "获取" + config.label + "详情失败",
      });
    }
  });

  // 新增
  app.post(
    "/add",
    {
      schema: {
        //可根据需要添加自定义的校验规则
      },
    },
    async (request, reply) => {
      try {
        const newData = {
          ...request.body,
          createdAt: new Date(),
        };

        const result = await collection.insertOne(newData);

        return reply.code(201).send({
          success: true,
          message: config.label + "新增成功",
          data: {
            id: result.insertedId,
            ...newData,
          },
        });
      } catch (error) {
        app.log.error("新增" + config.label + "失败:", error);
        return reply.code(500).send({
          success: false,
          error: "新增" + config.label + "失败",
        });
      }
    }
  );

  // 更新
  app.post("/update/:id", async (request, reply) => {
    try {
      const { ObjectId } = app.mongo;
      const updateData = {
        ...request.body,
        updatedAt: new Date(),
      };

      const result = await collection.updateOne(
        { _id: new ObjectId(request.params.id) },
        { $set: updateData }
      );

      if (result.modifiedCount === 0) {
        return reply.code(404).send({
          success: false,
          error: config.label + "不存在或未修改",
        });
      }

      return {
        success: true,
        message: config.label + "更新成功",
      };
    } catch (error) {
      app.log.error("更新" + config.label + "失败:", error);
      return reply.code(500).send({
        success: false,
        error: "更新" + config.label + "失败",
      });
    }
  });

  // 删除
  app.post("/delete/:id", async (request, reply) => {
    try {
      const { ObjectId } = app.mongo;

      const result = await collection.deleteOne({
        _id: new ObjectId(request.params.id),
      });

      if (result.deletedCount === 0) {
        return reply.code(404).send({
          success: false,
          error: config.label + "不存在",
        });
      }

      return {
        success: true,
        message: config.label + "删除成功",
      };
    } catch (error) {
      app.log.error("删除" + config.label + "失败:", error);
      return reply.code(500).send({
        success: false,
        error: "删除" + config.label + "失败",
      });
    }
  });
}
